package com.besall.allbase.view.activity.chipstoollevel4.protocol.Settings;

import static bb.lanxing.lib.devices.sprint.entity.SettingSupports.SUPPORT_ITEM_NICK_NAME;
import static com.bes.bessdk.BesSdkConstants.BES_CONNECT_ERROR;
import static com.bes.bessdk.BesSdkConstants.BES_CONNECT_SUCCESS;
import static com.bes.bessdk.BesSdkConstants.BES_GATT_DESCRIPTOR_OTA_UUID;
import static com.bes.sdk.message.Constants.APP_UNBIND_DEVICE_SUCCESS;
import static com.bes.sdk.message.Constants.SAVE_PANELS_JSON_FILE_SUCCESS;
import static com.bes.sdk.message.Constants.SAVE_SETTINGS_JSON_FILE_SUCCESS;
import static com.bes.sdk.message.Constants.SAVE_USER_PROFILE_JSON_FILE_SUCCESS;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.INFO_Unbind_BT;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.KEY_TEST_GET_LOG_FILE;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.KEY_TEST_GET_LOG_FILE_NAME;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.RECEIVE_DATA_LOG;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.RETURN_SEND_LOG;
import static com.besall.allbase.common.utils.ActivityUtils.showToast;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothProfile;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.MenuProvider;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.databinding.unit.HeightUnit;
import bb.lanxing.databinding.unit.SpeedUnit;
import bb.lanxing.databinding.unit.UnitConstants;
import bb.lanxing.databinding.unit.WeightUnit;
import bb.lanxing.device.sgdevcie.setting.fragment.HeartRateChooseType;
import bb.lanxing.device.sgdevcie.setting.fragment.adapter.GearAdapter;
import bb.lanxing.device.sgdevcie.utils.SGDeviceSettingSupportUtil;
import bb.lanxing.devicelist.XZDeviceListActivity;
import bb.lanxing.lib.devices.sgsettingentity.gearprofile.Gear;
import bb.lanxing.lib.devices.sgsettingentity.setting.CommonSettings;
import bb.lanxing.lib.devices.sgsettingentity.setting.PanelModel;
import bb.lanxing.lib.devices.sgsettingentity.setting.Settings;
import bb.lanxing.lib.devices.sgsettingentity.setting.SettingsParams;
import bb.lanxing.lib.devices.sgsettingentity.setting.User;
import bb.lanxing.lib.devices.sgsettingentity.userprofile.UserProfileSettings;
import bb.lanxing.lib.devices.sprint.entity.SettingSupports;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.database.Device;
import bb.lanxing.network.BiCiCallback;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.util.DialogUtil;
import bb.lanxing.util.InputHelper;
import bb.lanxing.view.dialog.AlertDialogBuilder;
import bb.lanxing.view.dialog.CircularProgressDialog;
import bb.lanxing.view.dialog.CommonDialogFragment;
import bb.lanxing.view.dialog.NumberPickerDialog;
import bb.lanxing.view.dialog.NumberUnitPickerDialog;
import com.bes.bessdk.BesSdkConstants;
import com.bes.bessdk.connect.BleConnector;
import com.bes.bessdk.scan.BtHeleper;
import com.bes.bessdk.service.base.BesServiceConfig;
import com.bes.bessdk.service.base.BesServiceListener;
import com.bes.sdk.device.HmDevice;
import com.bes.sdk.message.Constants;
import com.bes.sdk.message.MsgStrAnalyzer;
import com.bes.sdk.utils.DeviceProtocol;
import com.bes.sdk.utils.SettingsJsonUtils;
import com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants;
import com.besall.allbase.bluetooth.service.Protocol.ProtocolService;
import com.besall.allbase.common.utils.FileUtils;
import com.besall.allbase.view.activity.chipstoollevel4.protocol.ProtocolPresenter;
import com.blankj.utilcode.util.ConvertUtils;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.umeng.socialize.net.dplus.CommonNetImpl;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import kotlin.collections.ArraysKt;
import kotlin.jvm.internal.Ref;
import org.litepal.LitePal;

public class SettingsActivity extends AppCompatActivity implements BesServiceListener {
	private static final String TAG = "SettingsActivity";
	private static final int REQ_WHEEL_CIRCUM_EDIT_CODE = 6;
	private static final String LAN_CHINESE = "zh-CN";
	private static final String LAN_ENGLISH = "en-US";
	// for settings.json
	static CommonSettings commonSettings;
	// for user_profile.json
	static UserProfileSettings userProfileSettings;
	static List<Gear> mGearList = null;
	public static PanelModel PANEL_MODEL;

	BesServiceConfig mServiceConfig;
	HmDevice mHmDevice;

	private boolean parseUserProfileJsonFile() {
		String device_model = SettingsJsonUtils.getDeviceModel(this);
		String sn = SettingsJsonUtils.getSn(this);

		String DirStr = FileUtils.checkExternalDirectoryPathExist(false, device_model, sn, SettingsJsonUtils.SETTINGS);
		if (DirStr == null) {
			Log.d(TAG, "parse user profile,the settings  dir is null,return ");
			return false;
		}
		String fileDirStr = FileUtils.checkExternalDirectoryPathExist(true, device_model, sn, SettingsJsonUtils.SETTINGS, SettingsJsonUtils.USERPROFILE_JSON);
		Log.d(TAG, "the file dir: " + fileDirStr);
		if (fileDirStr != null) {
			userProfileSettings = createUserProfileFromFile(fileDirStr);
			if (userProfileSettings == null) {
				return false;
			}
			Log.d(TAG, "the user profile  info: " + userProfileSettings);
		}
		return true;
	}

	public static UserProfileSettings createUserProfileFromFile(String str) {
		try {
			Gson gson = new Gson();
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(str)));
			StringBuilder sb = new StringBuilder();
			while (true) {
				String readLine = bufferedReader.readLine();
				if (readLine != null) {
					sb.append(readLine);
				} else {
					String sb2 = sb.toString();
					Log.d(TAG, "parse user profile settings json str:" + sb2);
					UserProfileSettings fromJson = gson.fromJson(sb2, UserProfileSettings.class);
					Log.d(TAG, "parse user profile settings. json str:" + fromJson.toString());
					return fromJson;
				}
			}
		} catch (JsonParseException | IOException e) {
			Log.d(TAG, "parse user_profile.json exception:");
			e.printStackTrace();
			return null;
		}
	}

	// add by wangsm for init the Settings
	public static Settings createSettingsFromFile(String str) {
		try {
			Gson gson = new Gson();
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(str)));
			StringBuilder sb = new StringBuilder();
			while (true) {
				String readLine = bufferedReader.readLine();
				if (readLine != null) {
					sb.append(readLine);
				} else {
					String sb2 = sb.toString();
					Log.d(TAG, "parse settings json str:" + sb2);
					// Intrinsics.checkNotNullExpressionValue(sb2, "stringBuilder.toString()");
					Settings fromJson = gson.fromJson(sb2, Settings.class);
					// Intrinsics.checkNotNullExpressionValue(fromJson, "gson.fromJson(json,
					// CommonSettings::class.java)");
					Log.d(TAG, "parse settings. json str:" + fromJson.toString());
					return fromJson;
				}
			}
		} catch (JsonParseException | IOException e) {
			Log.d(TAG, "parse settings.json exception:");
			e.printStackTrace();
			return null;
		}
	}

	// end user profile

	@Override protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings_activity);
		Toolbar toolbar = findViewById(R.id.toolbar);
		setSupportActionBar(toolbar);
		ActionBar actionBar = getSupportActionBar();
		if (actionBar != null) {
			actionBar.setDisplayHomeAsUpEnabled(true);
		}
		addMenuProvider(new MenuProvider() {
			@Override public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater menuInflater) {
			}

			@Override public boolean onMenuItemSelected(@NonNull MenuItem menuItem) {
				if (menuItem.getItemId() == android.R.id.home) {
					List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
					if (fragmentList.size() == 1) {
						boolean backQuit = fragmentList.get(0).getClass().getSimpleName().equals(SettingsFragment.class.getSimpleName());
						if (backQuit) {
							finish();
						} else {
							getSupportFragmentManager().popBackStack();
						}
						return true;
					}
				}
				return false;
			}
		}, this);
		if (savedInstanceState == null) {
			boolean isSetting = getIntent().getBooleanExtra("IS_SETTING", false);
			BaseSettingsFragment baseSettingsFragment = new SettingsFragment();
			baseSettingsFragment.setActionBar(actionBar);
			getSupportFragmentManager().beginTransaction().replace(R.id.settings, baseSettingsFragment).commit();
		}
		initServiceConf();
		ProtocolPresenter protocolPresenter = ProtocolPresenter.getInstance();
		protocolPresenter.setProtocolServiceListener(this);
	}

	// init the bes service config when connect the device
	void initServiceConf() {
		Intent intent = getIntent();
		if (intent != null) {
			// deviceName = intent.getStringExtra("DEVICE_NAME");
			// deviceAddr = intent.getStringExtra("DEVICE_ADDRESS");
			Bundle bundle = intent.getBundleExtra("BUNDLE_CONTENT");
			if (bundle != null) {
				mHmDevice = (HmDevice) bundle.getSerializable("HM_DEVICE");
			}
		}
		mServiceConfig = new BesServiceConfig();
		mServiceConfig.setDeviceProtocol(DeviceProtocol.PROTOCOL_BLE);
		mServiceConfig.setTotaConnect(false);
		mServiceConfig.setUseTotaV2(false);
		mServiceConfig.setServiceUUID(BesSdkConstants.ALIPAY_SERIVICE_UUID);
		mServiceConfig.setCharacteristicsUUID(BesSdkConstants.ALIPAY_CHARACTERISTICRX_UUID);// ALIPAY_CHARACTERISTICRX_UUID
		// mServiceConfig.setCharacteristicsTX(BesSdkConstants.ALIPAY_CHARACTERISTICTX_UUID);
		mServiceConfig.setDescriptorUUID(BES_GATT_DESCRIPTOR_OTA_UUID);
		mServiceConfig.setDevice(mHmDevice);
	}

	@Override public void onTotaConnectState(boolean state, HmDevice hmDevice) {
		Log.d(TAG, "wangsm_bes,settings onTotaConnectState");
	}

	@Override public void onErrorMessage(int msg, HmDevice hmDevice) {
		Log.d(TAG, "wangsm_bes,settings onErrorMessage:" + msg);
	}

	private boolean parseSettingsJsonFile() {
		String device_model = SettingsJsonUtils.getDeviceModel(this);
		String sn = SettingsJsonUtils.getSn(this);
		String DirStr = FileUtils.checkExternalDirectoryPathExist(false, device_model, sn, SettingsJsonUtils.SETTINGS);

		if (DirStr == null) {
			Log.d(TAG, "the settings  dir is null,return ");
			return false;
		}
		String fileDirStr = FileUtils.checkExternalDirectoryPathExist(true, device_model, sn, SettingsJsonUtils.SETTINGS, SettingsJsonUtils.SETTING_JSON);
		Log.d(TAG, "the file dir: " + fileDirStr);
		if (fileDirStr != null) {
			Settings settings = FileUtils.parseFromFile(fileDirStr, Settings.class);
			if (settings == null) {
				return false;
			}
			Log.d(TAG, "the settings info: " + settings);
			initSettingsData(settings);
		}
		return true;
	}

	private void initSettingsData(Settings settings) {
		// User
		String platform = "Bes";
		if (settings == null) {
			Log.e(TAG, "initSettingsData the settings obj is null,return");
			return;
		}
		bb.lanxing.model.database.User userInfo = App.getInstance().getSigninUser();
		if (null == userInfo) {
			Log.e(TAG, "initSettingsData userInfo is null,return");
		}

		User user = new User(platform, userInfo.getUid(), userInfo.getName());
		String device_model = SettingsJsonUtils.getDeviceModel(this);
		String sn = SettingsJsonUtils.getSn(this);
		commonSettings = new CommonSettings(device_model, settings, sn, Long.parseLong(settings.getUpdate_at()), user);
	}

	// end by wangsm
	@Override public void onStateChangedMessage(int msg, String msgStr, HmDevice hmDevice) {
		runOnUiThread(() -> {
			if (msg == BES_CONNECT_SUCCESS) {
				Log.d(TAG, "wangsm_bes,settings onStateChangedMessage, , BES_CONNECT_SUCCESS msgStr: " + msgStr);
				// initSettingsData();
			}
			if (msg == BES_CONNECT_ERROR) {
				Log.d(TAG, "wangsm_bes,settings onStateChangedMessage, BES_CONNECT_ERROR msgStr: " + msgStr);
				showToast(msgStr);
				Intent intent = new Intent(getApplicationContext(), XZDeviceListActivity.class);
				startActivity(intent);
				finish();
			}

			if (msg == RECEIVE_DATA_LOG) {
				Log.d(TAG, "wangsm_bes,settings onStateChangedMessage, RECEIVE_DATA_LOG msgStr: " + msgStr);
			}
			if (msg == RETURN_SEND_LOG) {
				Log.d(TAG, "wangsm_bes,settings onStateChangedMessage, RETURN_SEND_LOG msgStr: " + msgStr);
			}
			if (msg == KEY_TEST_GET_LOG_FILE_NAME) {
				Log.d(TAG, "wangsm_bes,settings onStateChangedMessage, KEY_TEST_GET_LOG_FILE_NAME msgStr: " + msgStr);
			}
			if (msg == KEY_TEST_GET_LOG_FILE) {
				Log.d(TAG, "wangsm_bes,settings onStateChangedMessage, KEY_TEST_GET_LOG_FILE msgStr: " + msgStr);
			}
		});
	}

	@Override public void onSuccessMessage(int msg, HmDevice hmDevice) {
		Log.d(TAG, "wangsm_bes,settings onSuccessMessage,msg: " + msg);
		runOnUiThread(() -> {
			if (msg == SAVE_SETTINGS_JSON_FILE_SUCCESS) {
				boolean result = parseSettingsJsonFile();
				if (result) {
					BaseSettingsFragment baseSettingsFragment = (BaseSettingsFragment) getSupportFragmentManager().findFragmentById(R.id.settings);
					if (baseSettingsFragment != null) {
						baseSettingsFragment.callBack("");
					}
				}
			} else if (msg == SAVE_USER_PROFILE_JSON_FILE_SUCCESS) {
				boolean result = parseUserProfileJsonFile();
				Log.d(TAG, "the result is : " + result);
				if (result) {
					UserProfileSettingsFragment userProfileSettingsFragment = (UserProfileSettingsFragment) getSupportFragmentManager().findFragmentById(R.id.settings);
					Log.d(TAG, "begin call back init userprofile settings ");
					if (userProfileSettingsFragment != null) {
						Log.d(TAG, "entry call back");
						userProfileSettingsFragment.callBack("");
					}
					Log.d(TAG, "end call back init userprofile settings ");
				}
			} else if (msg == SAVE_PANELS_JSON_FILE_SUCCESS) {
				Log.i(TAG, "onSuccessMessage, begin parse panels.json ");
				BaseSettingsFragment baseSettingsFragment = (BaseSettingsFragment) getSupportFragmentManager().findFragmentById(R.id.settings);
				if (null != baseSettingsFragment) {
					baseSettingsFragment.dismissLoading();
				}
				parseFile();
			} else if (msg == APP_UNBIND_DEVICE_SUCCESS) {
				Log.i(TAG, "onSuccessMessage, unbind device success ");
				SettingsFragment settingsFragment = (SettingsFragment) getSupportFragmentManager().findFragmentById(R.id.settings);
				if (null != settingsFragment) {
					settingsFragment.unBindFinish();
				}
			}
		});
	}

	private void parseFile() {
		String device_model = SettingsJsonUtils.getDeviceModel(this);
		String sn = SettingsJsonUtils.getSn(this);
		String devicePanelFolderPath = FileUtils.checkExternalDirectoryPathExist(false, device_model, sn, SettingsJsonUtils.SETTINGS);
		File profileFile = new File(devicePanelFolderPath, SettingsJsonUtils.PANEL_JSON);
		if (profileFile.exists()) {
			PANEL_MODEL = FileUtils.parseFromFile(profileFile.getPath(), PanelModel.class);
		}
	}

	public static class SettingsFragment extends BaseSettingsFragment implements View.OnClickListener {
		LinearLayout userInforView;
		LinearLayout gearInforView;
		TextView backlightView;
		TextView keytoneView;
		TextView autoStopView;
		TextView languageView;
		TextView unitView;
		TextView temperatureView;
		LinearLayout factoryResetView;
		LinearLayout unbindDeviceView;
		TextView settingResetView;
		Context mContext;
		private View mRootView;

		@Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			mContext = inflater.getContext();
			if (null == mRootView) {
				mRootView = inflater.inflate(R.layout.fragment_bes_device_setting_entry, container, false);
			}
			ActionBar actionBar = getActionBar();
			if (null != actionBar) {
				actionBar.setTitle(R.string.device_setting);
			}
			return mRootView;
		}

		@Override public void onActivityCreated(@Nullable Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
			if (activity == null) {
				activity = requireActivity();
			}

			userInforView = activity.findViewById(R.id.user_infor);
			userInforView.setOnClickListener(this);

			gearInforView = activity.findViewById(R.id.gear_info_ll);
			gearInforView.setOnClickListener(this);

			backlightView = activity.findViewById(R.id.backlight_id);
			backlightView.setOnClickListener(this);

			keytoneView = activity.findViewById(R.id.keytone_id);
			keytoneView.setOnClickListener(this);

			autoStopView = activity.findViewById(R.id.autostop_id);
			autoStopView.setOnClickListener(this);

			languageView = activity.findViewById(R.id.language_id);
			languageView.setOnClickListener(this);

			unitView = activity.findViewById(R.id.unit_id);
			unitView.setOnClickListener(this);

			temperatureView = activity.findViewById(R.id.temparature_id);
			temperatureView.setOnClickListener(this);

			unbindDeviceView = activity.findViewById(R.id.unbind_device_ll);
			unbindDeviceView.setOnClickListener(this);

			factoryResetView = activity.findViewById(R.id.factory_reset_id);
			factoryResetView.setOnClickListener(this);

			settingResetView = activity.findViewById(R.id.settings_reset);
			settingResetView.setOnClickListener(this);

			ProtocolPresenter protocolPresenter = ProtocolPresenter.getInstance();
			ProtocolService protocolService = protocolPresenter.getProtocolService();
			int state = protocolService.getDeviceConnectState();
			if (state != BluetoothProfile.STATE_CONNECTED) {
				showToast(R.string.pls_conn_device);
				return;
			}
			syncSettings();
		}

		@Override public void onClick(View v) {
			if (v.getId() == R.id.user_infor) {
				Log.d(TAG, "wangsm_bes,settings, get user info request");
				// protocolPresenter.sendInfoData(ProtocolConstants.INFO_Get_personal_information,null);
				goTargetFragment(new UserProfileSettingsFragment());
			} else if (v.getId() == R.id.gear_info_ll) {
				goTargetFragment(new GearSettingsFragment());
			} else if (v.getId() == R.id.backlight_id) {
				showBacklightPopupMenu();
			} else if (v.getId() == R.id.keytone_id) {
				showKeyTonePopupMenu();
			} else if (v.getId() == R.id.autostop_id) {
				showAutoPausePopupMenu();
			} else if (v.getId() == R.id.language_id) {
				showLanguagePopupMenu();
			} else if (v.getId() == R.id.unit_id) {
				showUnitPopupMenu();
			} else if (v.getId() == R.id.temparature_id) {
				showTemperaturePopupMenu();
			} else if (v.getId() == R.id.factory_reset_id) {
				new CommonDialogFragment(R.layout.dialog_setting_factory_reset, (v1, dialogFragment) -> {
					Button negativeBtn = v1.findViewById(R.id.negativeBtn);
					Button positiveBtn = v1.findViewById(R.id.positiveBtn);

					negativeBtn.setOnClickListener(view -> {
						dialogFragment.dismissAllowingStateLoss();
					});
					positiveBtn.setOnClickListener(view -> {
						dialogFragment.dismissAllowingStateLoss();
						sendFactoryResetCmd();
					});
				}).setMargin(ConvertUtils.dp2px(10f)).show(getParentFragmentManager());
			} else if (v.getId() == R.id.unbind_device_ll) {
				unBindDeviceCmd();
			} else if (v.getId() == R.id.settings_reset) {
				new CommonDialogFragment(R.layout.dialog_setting_reset, (v1, dialogFragment) -> {
					Button negativeBtn = v1.findViewById(R.id.negativeBtn);
					Button positiveBtn = v1.findViewById(R.id.positiveBtn);

					negativeBtn.setOnClickListener(view -> {
						dialogFragment.dismissAllowingStateLoss();
					});
					positiveBtn.setOnClickListener(view -> {
						dialogFragment.dismissAllowingStateLoss();
						sendSettingsResetCmd();
					});
				}).setMargin(ConvertUtils.dp2px(10f)).show(getParentFragmentManager());
			}
		}

		private void showLoading(int id) {
			if (progressDialog == null) {
				progressDialog = new CircularProgressDialog(mContext, false, false, null);
			}
			progressDialog.show(id);
		}

		@Override public void callBack(String data) {
			Log.d(TAG, "wangsm_bes,the SettingsFragment call back");
			if (progressDialog != null) {
				progressDialog.dismiss();
			}
			initSettingsView();
		}

		private void initSettingsView() {
			Settings settings = commonSettings.getSettings();
			String[] backlightArray = getResources().getStringArray(R.array.backlight_array);
			String[] onOffArray = getResources().getStringArray(R.array.on_off_array);
			String[] languageArray = getResources().getStringArray(R.array.language_array);
			String[] unitArray = getResources().getStringArray(R.array.unit_array);
			String[] tempUnitArray = getResources().getStringArray(R.array.temperature_unit_array);

			// backlight
			backlightView.setText(backlightArray[settings.getBacklight()]);
			// keytone
			Log.d(TAG, "the keytone is: " + settings.getKeytone());
			if (settings.getKeytone() == 0) {
				keytoneView.setText(onOffArray[0]);
			} else {
				keytoneView.setText(onOffArray[1]);
			}
			// autopause
			autoStopView.setText(onOffArray[settings.getAuto_pause()]);
			// language
			if (settings.getLanguage().equals(LAN_CHINESE)) {
				languageView.setText(languageArray[1]);
			} else {// en_US
				languageView.setText(languageArray[0]);
			}
			// unit
			unitView.setText(unitArray[settings.getUnit()]);
			// temperature
			temperatureView.setText(tempUnitArray[settings.getTemperature_unit()]);
		}

		/* execute the request cmd list */
		private void syncSettings() {
			if (progressDialog == null) {
				progressDialog = new CircularProgressDialog(mContext, true, true, null);
			}
			progressDialog.show(R.string.dialog_loading);
			Log.d(TAG, "begin get settings info ");
			String device_model = SettingsJsonUtils.getDeviceModel(requireContext());
			String sn = SettingsJsonUtils.getSn(requireContext());
			MsgStrAnalyzer.setMsgCallBackId(Constants.SAVE_SETTINGS_JSON_FILE_SUCCESS);
			ProtocolPresenter protocolPresenter = ProtocolPresenter.getInstance();
			protocolPresenter.getBikeWatchDataFromBesClient(ProtocolConstants.BIKEWATCH_get_settings_info, device_model, sn);
		}

		// save the settings to json file settings.json
		private void saveSettingsJson() {
			ProtocolPresenter protocolPresenter = ProtocolPresenter.getInstance();
			ProtocolService protocolService = protocolPresenter.getProtocolService();
			int state = protocolService.getDeviceConnectState();
			if (state != BluetoothProfile.STATE_CONNECTED) {
				showToast(R.string.pls_conn_device);
				return;
			}
			Calendar calendar = Calendar.getInstance();
			long updateTime = calendar.getTimeInMillis();
			commonSettings.setUpdated_at(updateTime);
			String jsonStr = FileUtils.createCommonSettingsJsonStr(commonSettings);
			boolean result = FileUtils.writeSettingsJsonStrToFile(activity, commonSettings.getDevice_model(), commonSettings.getSn(), jsonStr, SettingsJsonUtils.SETTING_JSON);
			if (result) {
				protocolPresenter.getBikeWatchDataFromBesClient(ProtocolConstants.BIKEWATCH_set_settings_info, commonSettings.getDevice_model(), commonSettings.getSn());// yjx
			}
		}

		/* show the backlight Dialog select. */
		public void showBacklightPopupMenu() {
			if (activity == null) {
				activity = requireActivity();
			}
			final Dialog dialog = new Dialog(activity);
			dialog.setContentView(R.layout.dialog_sprint_settings_backlight);
			Window window = dialog.getWindow();
			WindowManager.LayoutParams attributes = window.getAttributes();
			attributes.gravity = Gravity.BOTTOM;
			attributes.width = WindowManager.LayoutParams.MATCH_PARENT;
			attributes.height = WindowManager.LayoutParams.WRAP_CONTENT;
			window.setAttributes(attributes);
			RadioGroup radioGroup = dialog.findViewById(R.id.rg_settings_items);

			radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
				Settings settings = commonSettings.getSettings();
				int i = settings.getBacklight();
				Log.d(TAG, "backlight click. checkedId= " + checkedId);
				if (checkedId == R.id.rb_sprint_settings_item_backlight_auto) {
					backlightView.setText(R.string.device_sprint_settings_backlight_auto);
					i = 2;
				} else if (checkedId == R.id.rb_sprint_settings_item_backlight_always) {
					i = 1;
					backlightView.setText(R.string.device_sprint_settings_backlight_always);
				} else if (checkedId == R.id.rb_sprint_settings_item_backlight_turn_off) {
					i = 0;
					backlightView.setText(R.string.device_sprint_settings_backlight_turn_off);
				}

				Log.d(TAG, "backlight click. i= " + i);
				if (settings.getBacklight() != i) {
					settings.setBacklight(i);
					commonSettings.setSettings(settings);
					saveSettingsJson();
				}

				dialog.dismiss();
			});
			dialog.show();
		}

		/* show the keytone sound pop menu */
		public void showKeyTonePopupMenu() {
			if (activity == null) {
				activity = requireActivity();
			}
			final Dialog dialog = new Dialog(activity);
			dialog.setContentView(R.layout.dialog_sprint_settings_switch);
			Window window = dialog.getWindow();
			WindowManager.LayoutParams attributes = window.getAttributes();
			attributes.gravity = Gravity.BOTTOM;
			attributes.width = WindowManager.LayoutParams.MATCH_PARENT;
			attributes.height = WindowManager.LayoutParams.WRAP_CONTENT;
			window.setAttributes(attributes);

			RadioGroup radioGroup = dialog.findViewById(R.id.rg_settings_items);
			radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
				int keytoneOn = 0;
				Settings settings = commonSettings.getSettings();
				if (checkedId == R.id.tv_sprint_settings_item_on) {
					keytoneOn = 1;
					keytoneView.setText(R.string.device_switch_on);
				} else if (checkedId == R.id.tv_sprint_settings_item_off) {
					keytoneView.setText(R.string.device_switch_off);
				}
				Log.d(TAG, "keytoneOn= " + keytoneOn);
				if (settings.getKeytone() != keytoneOn) {
					settings.setKeytone(keytoneOn);
					commonSettings.setSettings(settings);
					saveSettingsJson();
				}

				dialog.dismiss();
			});
			dialog.show();
		}

		public void showAutoPausePopupMenu() {
			if (activity == null) {
				activity = requireActivity();
			}
			final Dialog dialog = new Dialog(activity);
			dialog.setContentView(R.layout.dialog_sprint_settings_switch);
			Window window = dialog.getWindow();
			WindowManager.LayoutParams attributes = window.getAttributes();
			attributes.gravity = Gravity.BOTTOM;
			attributes.width = WindowManager.LayoutParams.MATCH_PARENT;
			attributes.height = WindowManager.LayoutParams.WRAP_CONTENT;
			window.setAttributes(attributes);
			RadioGroup radioGroup = dialog.findViewById(R.id.rg_settings_items);
			radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
				// boolean z = false;
				int autoPauseOn = 0;
				Settings settings = commonSettings.getSettings();
				if (checkedId == R.id.tv_sprint_settings_item_on) {
					// z = true;
					autoPauseOn = 1;
					autoStopView.setText(R.string.device_switch_on);
				} else if (checkedId == R.id.tv_sprint_settings_item_off) {
					autoPauseOn = 0;
					autoStopView.setText(R.string.device_switch_off);
				}

				Log.d(TAG, "autoPauseOn= " + autoPauseOn);

				if (settings.getAuto_pause() != autoPauseOn) {
					settings.setAuto_pause(autoPauseOn);
					commonSettings.setSettings(settings);
					saveSettingsJson();
				}
				dialog.dismiss();
			});
			dialog.show();
		}

		public void showLanguagePopupMenu() {
			if (activity == null) {
				activity = requireActivity();
			}
			final Dialog dialog = new Dialog(activity);
			dialog.setContentView(R.layout.dialog_sprint_settings_language);
			Window window = dialog.getWindow();
			WindowManager.LayoutParams attributes = window.getAttributes();
			attributes.gravity = Gravity.BOTTOM;
			attributes.width = WindowManager.LayoutParams.MATCH_PARENT;
			attributes.height = WindowManager.LayoutParams.WRAP_CONTENT;
			window.setAttributes(attributes);

			RadioGroup radioGroup = dialog.findViewById(R.id.rg_settings_items);

			radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
				String languange = LAN_ENGLISH;
				Settings settings = commonSettings.getSettings();
				if (checkedId == R.id.rb_sprint_settings_item_language_chinese) {
					languageView.setText(R.string.device_sprint_settings_language_chinese);
					languange = LAN_CHINESE;
				} else if (checkedId == R.id.rb_sprint_settings_item_language_english) {
					languageView.setText(R.string.device_sprint_settings_language_english);
					languange = LAN_ENGLISH;
				}
				Log.d(TAG, "languange= " + languange);
				if (!settings.getLanguage().equals(languange)) {
					settings.setLanguage(languange);
					commonSettings.setSettings(settings);
					saveSettingsJson();
				}

				dialog.dismiss();
			});
			dialog.show();
		}

		public void showUnitPopupMenu() {
			if (activity == null) {
				activity = requireActivity();
			}
			final Dialog dialog = new Dialog(activity);
			dialog.setContentView(R.layout.dialog_sprint_settings_unit);
			Window window = dialog.getWindow();
			WindowManager.LayoutParams attributes = window.getAttributes();
			attributes.gravity = Gravity.BOTTOM;
			attributes.width = WindowManager.LayoutParams.MATCH_PARENT;
			attributes.height = WindowManager.LayoutParams.WRAP_CONTENT;
			window.setAttributes(attributes);

			RadioGroup radioGroup = dialog.findViewById(R.id.rg_settings_items);

			radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
				int unit = 0;
				Settings settings = commonSettings.getSettings();
				if (checkedId == R.id.rb_sprint_settings_item_unit_metric) {
					unitView.setText(R.string.device_sprint_settings_unit_metric);
				} else if (checkedId == R.id.rb_sprint_settings_item_unit_british) {
					unitView.setText(R.string.device_sprint_settings_unit_british);
					unit = 1;
				}

				Log.d(TAG, "unit= " + unit);

				if (settings.getUnit() != unit) {
					settings.setUnit(unit);
					commonSettings.setSettings(settings);
					saveSettingsJson();
				}

				dialog.dismiss();
			});
			dialog.show();
		}

		private void sendSettingsResetCmd() {
			ProtocolPresenter protocolPresenter = ProtocolPresenter.getInstance();
			if (protocolPresenter != null) {
				Log.d(TAG, "begin send settings reset cmd");
				showLoading(R.string.dialog_reset_loading);
				Settings settings = commonSettings.getSettings();
				settings.setSettings_reset(1);
				commonSettings.setSettings(settings);
				saveSettingsJson();
				//protocolPresenter.getBikeWatchDataFromBesClient(ProtocolConstants.BIKEWATCH_Reset_settings, device_model, sn);
			}
		}

		private void unBindDeviceCmd() {
			ArrayList<HmDevice> curConBleDevices = BleConnector.getsConnector(requireActivity(), null, null).getCurConnectDevices();
			ProtocolPresenter protocolPresenter = ProtocolPresenter.getInstance();
			if (protocolPresenter != null && curConBleDevices != null && !curConBleDevices.isEmpty()) {
				Log.d(TAG, "unbind the device.");
				protocolPresenter.sendInfoData(INFO_Unbind_BT, null);
			}
		}

		public void unBindFinish() {
			ArrayList<HmDevice> curConBleDevices = BleConnector.getsConnector(requireActivity(), null, null).getCurConnectDevices();
			ProtocolPresenter protocolPresenter = ProtocolPresenter.getInstance();
			if (protocolPresenter != null && curConBleDevices != null && !curConBleDevices.isEmpty()) {
				Log.d(TAG, "unbind the device finish");
				HmDevice hmDevice = curConBleDevices.get(0);
				String address = hmDevice.getBleAddress();
				BtHeleper.unBondedBleDevice(requireActivity(), address);
				Device.deleteByAddress(address);
			}
		}

		private void sendFactoryResetCmd() {
			Log.d(TAG, "sendFactoryResetCmd");
			ProtocolPresenter protocolPresenter = ProtocolPresenter.getInstance();
			if (protocolPresenter != null) {
				// showLoading(R.string.dialog_reset_loading);

				Log.d(TAG, "begin send factory reset cmd");
				showLoading(R.string.dialog_reset_loading);
				Settings settings = commonSettings.getSettings();
				settings.setFactory_reset(1);
				commonSettings.setSettings(settings);
				saveSettingsJson();
				//protocolPresenter.getBikeWatchDataFromBesClient(ProtocolConstants.BIKEWATCH_Reset_device, device_model, sn);
			}
		}

		public void showTemperaturePopupMenu() {
			if (activity == null) {
				activity = requireActivity();
			}
			final Dialog dialog = new Dialog(activity);
			dialog.setContentView(R.layout.dialog_sprint_settings_temperature);
			Window window = dialog.getWindow();
			WindowManager.LayoutParams attributes = window.getAttributes();
			attributes.gravity = Gravity.BOTTOM;
			attributes.width = WindowManager.LayoutParams.MATCH_PARENT;
			attributes.height = WindowManager.LayoutParams.WRAP_CONTENT;
			window.setAttributes(attributes);

			RadioGroup radioGroup = dialog.findViewById(R.id.rg_settings_items);

			radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
				int temperatureUnit = 0;
				Settings settings = commonSettings.getSettings();
				if (checkedId == R.id.rb_sprint_settings_item_unit_hot) {
					temperatureView.setText(R.string.unit_hots);
					temperatureUnit = 0;
				} else if (checkedId == R.id.rb_sprint_settings_item_unit_f_hot) {
					temperatureView.setText(R.string.unit_F_hots);
					temperatureUnit = 1;
				}

				Log.d(TAG, "temperatureUnit= " + temperatureUnit);
				if (settings.getTemperature_unit() != temperatureUnit) {
					settings.setTemperature_unit(temperatureUnit);
					commonSettings.setSettings(settings);
					saveSettingsJson();
				}

				dialog.dismiss();
			});
			dialog.show();
		}
	}

	// SettingsFragment
	public static class UserProfileSettingsFragment extends BaseSettingsFragment implements View.OnClickListener {

		LinearLayout userProfileGenderView;
		TextView gender;
		LinearLayout birthdayLLView;
		LinearLayout heightLLView;
		TextView heightTextView;

		LinearLayout weightLLView;
		TextView weightTextView;

		TextView birthdayView;

		LinearLayout maxHeartRateLLView;
		TextView maxHeartRateTextView;

		LinearLayout lthrLLView;
		TextView lthrTextView;

		LinearLayout ftpLLView;
		TextView ftpTextView;

		LinearLayout heartRateLLView;
		TextView heartRateTextView;

		LinearLayout speedWarningLLView;
		TextView speedWarningTextView;

		LinearLayout setTimeZoneLLView;
		TextView timeZoneTextView;
		NumberUnitPickerDialog heightPickerDialog;
		NumberUnitPickerDialog weightPickerDialog;
		NumberUnitPickerDialog hrPicker;
		NumberUnitPickerDialog ftpPicker;
		NumberUnitPickerDialog speedPicker;
		NumberPickerDialog timeZonePickerDialog;

		@Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			return inflater.inflate(R.layout.fragment_sg_user_profile_settings, container, false);
		}

		private void sendGetUserProfileCmd() {
			Log.d(TAG, "send the get personal info");
			if (activity == null) {
				activity = requireActivity();
			}
			showLoading(activity, R.string.dialog_loading);
			String device_model = SettingsJsonUtils.getDeviceModel(requireContext());
			String sn = SettingsJsonUtils.getSn(requireContext());
			ProtocolPresenter protocolPresenter = ProtocolPresenter.getInstance();
			protocolPresenter.getBikeWatchDataFromBesClient(ProtocolConstants.BIKEWATCH_get_personal_info, device_model, sn);
		}

		@Override public void onActivityCreated(@Nullable Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
			if (activity == null) {
				activity = requireActivity();
			}

			userProfileGenderView = activity.findViewById(R.id.user_profile_gender_ll);
			userProfileGenderView.setOnClickListener(this);
			gender = activity.findViewById(R.id.gender);

			// the birthday view
			birthdayLLView = activity.findViewById(R.id.birthday_ll);
			birthdayLLView.setOnClickListener(this);
			birthdayView = activity.findViewById(R.id.birthday_view);
			/*
			 * Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis());//this
			 * need to get the db data,for birthday display,if exist. Date date = calendar.getTime(); SimpleDateFormat
			 * simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); String birthday = simpleDateFormat.format(date);
			 * Log.d(TAG,"wangsm_bes, birthday:  "+ birthday);
			 *//*
			 * StringBuffer sb = new StringBuffer(); sb.append(calendar.get(1)); sb.append(LINE);
			 * sb.append(calendar.get(2)+1); sb.append(LINE); sb.append(calendar.get(5));
			 *//*
			 * // birthdayView.setText(sb.toString()); birthdayView.setText(birthday);
			 */
			// the height view
			heightLLView = activity.findViewById(R.id.height_ll);
			heightLLView.setOnClickListener(this);
			heightTextView = activity.findViewById(R.id.height_view);

			// the weight view
			weightLLView = activity.findViewById(R.id.weight_ll);
			weightLLView.setOnClickListener(this);
			weightTextView = activity.findViewById(R.id.weight_view);

			// max heartrate
			maxHeartRateLLView = activity.findViewById(R.id.max_heartrate_ll);
			maxHeartRateLLView.setOnClickListener(this);
			maxHeartRateTextView = activity.findViewById(R.id.max_heart_rate);

			// lthr
			lthrLLView = activity.findViewById(R.id.lthr_ll);
			lthrLLView.setOnClickListener(this);
			lthrTextView = activity.findViewById(R.id.lthr_view);

			// ftp
			ftpLLView = activity.findViewById(R.id.ftp_ll);
			ftpLLView.setOnClickListener(this);
			ftpTextView = activity.findViewById(R.id.ftp_view);

			// heartrate
			heartRateLLView = activity.findViewById(R.id.heartrate_ll);
			heartRateLLView.setOnClickListener(this);
			heartRateTextView = activity.findViewById(R.id.heartrate_view);

			// speed warning
			speedWarningLLView = activity.findViewById(R.id.speed_warning_ll);
			speedWarningLLView.setOnClickListener(this);
			speedWarningTextView = activity.findViewById(R.id.speed_warning_view);

			// settimezone
			setTimeZoneLLView = activity.findViewById(R.id.set_timezone_ll);
			setTimeZoneLLView.setOnClickListener(this);
			timeZoneTextView = activity.findViewById(R.id.txt_tz);
			// parseUserProfileJsonFileTest(activity.getSupportFragmentManager());
			// parseUserProfileJsonFile();//test
			sendGetUserProfileCmd();
		}

		public void initUerProfileViews() {
			long userId = SharedManager.getInstance().getUserId();
			if (0 == userId) {
				requireActivity().finish();
				return;
			}
			bb.lanxing.model.database.User signinUser = bb.lanxing.model.database.User.getUserByUid(userId);
			boolean settingChanged = false;

			String userPhone = SharedManager.getInstance().getUserPhone();
			TextView tv_name = activity.findViewById(R.id.tv_name);
			String userName = userProfileSettings.getUser_name();
			if (!TextUtils.isEmpty(userPhone)) {
				tv_name.setText(userPhone);
				if (!userName.equals(userPhone)) {
					userProfileSettings.setUser_name(userPhone);
					settingChanged = true;
				}
			}
			int userUid = signinUser.getUid();

			int uid = userProfileSettings.getUid();
			if (userUid != uid) {
				userProfileSettings.setUid(userUid);
				settingChanged = true;
			}

			// gender
			String[] strArr = {
				activity.getResources().getString(R.string.gender_female), activity.getResources().getString(R.string.gender_male)
			};
			// 用户的设置为准
			int userGender = signinUser.getGender();
			if (userGender != userProfileSettings.getGender()) {
				userProfileSettings.setGender(userGender);
				settingChanged = true;
			}
			String genderStr = strArr[userGender];
			gender.setText(genderStr);

			// birthday
			Calendar calendar = Calendar.getInstance();
			/*
			 * calendar.setTimeInMillis(System.currentTimeMillis());//this need to get the db data,for birthday
			 * display,if exist. Date date = calendar.getTime(); SimpleDateFormat simpleDateFormat = new
			 * SimpleDateFormat("yyyy-MM-dd"); String birthday = simpleDateFormat.format(date);
			 */
			Log.d(TAG, "wangsm_bes, birthday:  in second:" + userProfileSettings.getBirthday());// userProfileSettings
			// userProfile
			long birthdayLongValue = userProfileSettings.getBirthday();
			long userBirthday = signinUser.getBirthday();
			if (birthdayLongValue != userBirthday) {
				userProfileSettings.setBirthday(userBirthday);
				settingChanged = true;
			}
			calendar.setTimeInMillis(userBirthday * 1000);
			Date date = calendar.getTime();
			String birthday = formatDate(date);
			int age = parseBirthdayToAge(date);
			if (age != userProfileSettings.getAge()) {
				userProfileSettings.setAge(age);
				settingChanged = true;
			}
			Log.d(TAG, "wangsm_bes, birthday:  " + birthday);
			birthdayView.setText(birthday);// from db

			// height
			int userHeight = signinUser.getHeight();
			if (userProfileSettings.getHeight() != userHeight) {
				userProfileSettings.setHeight(userHeight);
				settingChanged = true;
			}
			heightTextView.setText(userHeight + "cm");// from db

			// weight
			float userWeight = (float) signinUser.getWeight();
			float weight = parseUserProfileWeight(userProfileSettings.getWeight());
			if (weight != userWeight) {
				userProfileSettings.setWeight((int) (userWeight * 1000));
				settingChanged = true;
			}
			weightTextView.setText(userWeight + "kg");// from db
			// max heart
			maxHeartRateTextView.setText(userProfileSettings.getMAXHR() + UnitConstants.getHeartRateUnit("m"));
			// lthr
			lthrTextView.setText(userProfileSettings.getLTHR() + UnitConstants.getHeartRateUnit("m"));
			// ftp
			ftpTextView.setText(userProfileSettings.getFTP() + "w");
			// heart rate
			heartRateTextView.setText(userProfileSettings.getALAHR() + UnitConstants.getHeartRateUnit("m"));
			// speed warning
			float alaspeed = parseUserProfileAlaSpeed(userProfileSettings.getALASPEED());
			speedWarningTextView.setText(alaspeed + UnitConstants.UNIT_SPEED_KMH);
			if (settingChanged) {
				saveUserProfileSettingsJson();
			}
			/*
			 * //time zone String timeZone = parseTimeZone(userProfileSettings.getTime_zone());
			 * timeZoneTextView.setText(timeZone);
			 */
		}

		@Override public void onClick(View v) {
			if (v.getId() == R.id.user_profile_gender_ll) {
				showGenderChooseDialog(activity);
				Log.d(TAG, "wangsm_bes,settings, get user info request");
				// protocolPresenter.sendInfoData(ProtocolConstants.INFO_Get_personal_information,null);
			} else if (v.getId() == R.id.birthday_ll) {
				showDatePicker();
			} else if (v.getId() == R.id.height_ll) {
				showHeightPicker(null);
			} else if (v.getId() == R.id.weight_ll) {
				showWeightPicker(null);
			} else if (v.getId() == R.id.max_heartrate_ll) {
				editMaxHeartRate();
			} else if (v.getId() == R.id.lthr_ll) {
				editLTHR();
			} else if (v.getId() == R.id.ftp_ll) {
				editFTP();
			} else if (v.getId() == R.id.heartrate_ll) {
				editAlertHeartRate();
			} else if (v.getId() == R.id.speed_warning_ll) {
				showSpeedDialog();
			} else if (v.getId() == R.id.set_timezone_ll) {
				editTimeZone();
			}
		}

		// parse userprofile weight to float
		private float parseUserProfileWeight(int userWeight) {// UserProfile userProfile
			float weight = 0.0f;
			int big = userWeight / 1000;
			float little = userWeight - big * 1000;
			float littleValue = little / 100;
			Log.d(TAG, "parseUserProfileWeight weight littleValue value: " + littleValue);
			weight = big + littleValue;
			Log.d(TAG, "parseUserProfileWeight weight weight value: " + weight);
			return weight;
		}

		// parse userprofile alaspeed to float
		private float parseUserProfileAlaSpeed(int alaspeed) {

			int highBit = alaspeed / 10;
			int lowBit = alaspeed - highBit * 10;

			float speed = (float) highBit + (float) lowBit / 10;
			return speed;
		}

		private String parseTimeZone(Long timezone) {
			// Long time_zone = timezone;
			String timezoneStr;
			StringBuilder sb = new StringBuilder();
			String valueOf;
			long j = 3600;
			long hValue = timezone / j;
			Log.d(TAG, "parseTimeZone, timezone.longValue(): " + timezone);
			Log.d(TAG, "parseTimeZone, longValue: " + hValue);
			// long minValue = (Math.abs(timezone.longValue()) - Math.abs(hValue))/60;
			long minValue = (Math.abs(timezone - hValue * j)) / 60;
			Log.d(TAG, "parseTimeZone, minValue: " + minValue);

			if (Math.abs(hValue) < 10) {
				sb.append('0');
			}

			sb.append(Math.abs(hValue));
			sb.append(":");
			sb.append(minValue);
			if (minValue == 0) {
				sb.append(minValue);
			}
			valueOf = sb.toString();
			Log.d(TAG, "parseTimeZone, valueOf: " + valueOf);
			if (hValue >= 0) {
				timezoneStr = '+' + valueOf;
			} else {
				timezoneStr = '-' + valueOf;
			}

			return timezoneStr;
		}

		// begin birthday
		private String formatDate(Date date) {
			String dateStr = null;
			DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			dateStr = simpleDateFormat.format(date);
			return dateStr;
		}

		private int parseBirthdayToAge(Date date) {
			if (date == null) {
				return 0;
			}
			LocalDate birthDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
			LocalDate currDate = LocalDate.now();
			Period period = Period.between(birthDate, currDate);
			Log.d(TAG, "the age is :" + period.getYears());
			return period.getYears();
		}

		public final void setBirthdayByByteStructs(Calendar calendar) {

			// int i = calendar.get(2);
			ByteBuffer allocate = ByteBuffer.allocate(4);
			Log.d(TAG, "wangsm_bes,calendar get1:  " + calendar.get(Calendar.YEAR));
			allocate.putShort((short) calendar.get(1));
			Log.d(TAG, "wangsm_bes,calendar get2:  " + calendar.get(Calendar.MONTH));
			allocate.put((byte) calendar.get(2));
			Log.d(TAG, "wangsm_bes,calendar get5:  " + calendar.get(Calendar.DATE));
			allocate.put((byte) (calendar.get(5) - 1));
			allocate.flip();
			int birthday = allocate.getInt();
			Log.d(TAG, "wangsm_bes,calendar birthday:  " + birthday);
		}
		// parse the date to age

		public final void showDatePicker() {
			// UserProfile userProfile = userProfileSettings.getUser_profile();
			final Calendar calendar = Calendar.getInstance();

			long birthdayLongValue = userProfileSettings.getBirthday();
			if (birthdayLongValue != 0) {
				calendar.setTimeInMillis(birthdayLongValue * 1000);
			} else {
				calendar.setTimeInMillis(System.currentTimeMillis());
			}

			new DatePickerDialog(requireContext(), (datePicker, i, i2, i3) -> {
				calendar.set(Calendar.YEAR, i);
				calendar.set(Calendar.MONTH, i2);
				calendar.set(Calendar.DATE, i3);
				long millis = calendar.getTimeInMillis();
				Log.d(TAG, "birthday set i: " + i + "i2: " + i2 + "13: " + i3);
				Log.d(TAG, "birthday millis: " + millis);
				Date date = calendar.getTime();
				String birthday = formatDate(date);
				birthdayView.setText(birthday);
				int age = parseBirthdayToAge(date);
				long value = millis / 1000;
				userProfileSettings.setAge(age);
				userProfileSettings.setBirthday(value);
				requestUpdate("birthday", String.valueOf(value));
				saveUserProfileSettingsJson();
			}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE)).show();
		}

		// show height dialog
		public final void showHeightPicker(final HeightUnit unit) {
			String type = "m";
			InputHelper.hideSoftInput(requireActivity());
			if (heightPickerDialog == null) {
				heightPickerDialog = new NumberUnitPickerDialog(getContext());
			}
			if (type.equals("m")) {
				heightPickerDialog.setMaxNumber(HeightUnit.LegalMetricMaxNum);
				heightPickerDialog.setMiniNumber(HeightUnit.LegalMetricMinNum);
				heightPickerDialog.setDefaultValue(userProfileSettings.getHeight());// userProfileSettings.getUser_profile().getHeight()
				heightPickerDialog.setUpUnitwithRange(UnitConstants.UNIT_SIZE_CM, null, 0, false);
			} else if (type.equals("f")) {
				heightPickerDialog.setMaxNumber(HeightUnit.LegalBritishMaxFTNum);
				heightPickerDialog.setMiniNumber(HeightUnit.LegalBritishMinFTNum);
				heightPickerDialog.setDefaultValue(userProfileSettings.getHeight());// userProfileSettings.getUser_profile().getHeight()
				heightPickerDialog.setUpUnitwithRange(UnitConstants.UNIT_SIZE_FT, "in", 12, false);
			}

			heightPickerDialog.setNumberPickListener(new NumberUnitPickerDialog.NumberPickListener() {
				@Override public void onDialogDismiss() {
				}

				@Override public void onNumberPick(float height, float decimal) {
					Log.d(TAG, "wangsm_bes, Height integer: " + height + "decimal: " + decimal);
					heightTextView.setText((int) height + UnitConstants.UNIT_SIZE_CM);
					int value = (int) height;
					userProfileSettings.setHeight(value);
					requestUpdate("height", String.valueOf(value));
					saveUserProfileSettingsJson();
				}
			});
			heightPickerDialog.show();
		}

		/// end birthday

		public final void showWeightPicker(final WeightUnit unit) {
			String type = "m";
			// UserProfile userProfile = userProfileSettings.getUser_profile();
			InputHelper.hideSoftInput(requireActivity());
			if (this.weightPickerDialog == null) {
				this.weightPickerDialog = new NumberUnitPickerDialog(getContext());
			}

			if (type.equals("m")) {
				weightPickerDialog.setMaxNumber(WeightUnit.LegalMetricMaxNum);
				weightPickerDialog.setMiniNumber(WeightUnit.LegalMetricMinNum);
				int value = userProfileSettings.getWeight();// userProfile
				int big = value / 1000;
				float little = value - big * 1000;
				float littleValue = little / 1000;
				Log.d(TAG, "the weight littleValue value: " + littleValue);
				float defaultValue = big + littleValue;
				Log.d(TAG, "the weight default value: " + defaultValue);
				weightPickerDialog.setDefaultValue(defaultValue);
				weightPickerDialog.setUpUnitwithRange(".", UnitConstants.UNIT_WEIGHT_KG, 10, false);
			} else if (type.equals("f")) {

			}

			weightPickerDialog.setNumberPickListener(new NumberUnitPickerDialog.NumberPickListener() {
				@Override public void onDialogDismiss() {
				}

				@Override public void onNumberPick(float f, float decimal) {
					weightTextView.setText(f + decimal / 10 + UnitConstants.UNIT_WEIGHT_KG);
					double weight = f * 1000 + decimal * 100;
					Log.d(TAG, "wangsm_bes,the weight: " + weight);
					requestUpdate("weight", String.valueOf(weight / 1000));
					userProfileSettings.setWeight((int) weight);
					saveUserProfileSettingsJson();
				}
			});
			weightPickerDialog.show();
		}
		// end show height dialog

		// show weight dialog

		// end weight
		// begin show HR dialog
		public final void showHRDialog(final HeartRateChooseType heartRateChooseType) {
			float intValue;
			boolean z;

			if (hrPicker == null) {
				hrPicker = new NumberUnitPickerDialog(getContext());
			}
			NumberUnitPickerDialog numberUnitPickerDialog = this.hrPicker;
			numberUnitPickerDialog.setNumberPickListener(new NumberUnitPickerDialog.NumberPickListener() {
				@Override public void onDialogDismiss() {
				}

				@Override public void onNumberPick(final float f, float decimal) {

					int num;
					// UserProfile userProfile = userProfileSettings.getUser_profile();
					Log.d(TAG, "wangsm_bes, heart rate " + "f: " + f + "f2: " + decimal);
					if (heartRateChooseType == HeartRateChooseType.HR) {
						num = userProfileSettings.getALAHR();// 100; //get the current hr from db or
						int temp = ((int) f);
						// bes;//user_profile4.getALAHR();
						if (num != temp) {// if the setting value is not equal the db or bes,need update it//
							// update the value to bes or db.
							heartRateTextView.setText(temp + UnitConstants.getHeartRateUnit("m"));
							userProfileSettings.setALAHR(temp);
						}
					} else if (heartRateChooseType == HeartRateChooseType.MAX) {
						num = userProfileSettings.getMAXHR();// 100;//get the current hr from db or
						// bes;//user_profile5.getMAXHR();
						int temp = ((int) f);
						if (num != temp) {// if the setting value is not equal the db or bes,need update it
							// update the value to bes or db.
							if (maxHeartRateTextView != null) {
								maxHeartRateTextView.setText(temp + UnitConstants.getHeartRateUnit("m"));
							}
							userProfileSettings.setMAXHR(temp);
						}
					} else {
						num = userProfileSettings.getLTHR();// 100;//get the current hr from db or
						// bes;////user_profile6.getLTHR();
						Log.d(TAG, "the lthr num: " + num);
						int temp = ((int) f);
						if (num != (temp)) { // if the setting value is not equal the db or bes,need update it
							// update the value to bes or db.
							if (lthrTextView != null) {
								lthrTextView.setText(temp + UnitConstants.getHeartRateUnit("m"));
							}
							userProfileSettings.setLTHR(temp);
						}
					}
					// save to json file
					// userProfileSettings.setUser_profile(userProfile);
					saveUserProfileSettingsJson();// userProfile
				}
			});

			numberUnitPickerDialog.setMaxNumber(220.0f);
			numberUnitPickerDialog.setMiniNumber(60.0f);
			if (heartRateChooseType == HeartRateChooseType.MAX) {
				numberUnitPickerDialog.setMaxNumber(220.0f);
				numberUnitPickerDialog.setMiniNumber(60.0f);
				intValue = userProfileSettings.getMAXHR();
				z = true;
			} else if (heartRateChooseType == HeartRateChooseType.LTHR) {
				numberUnitPickerDialog.setMaxNumber(200.0f);
				numberUnitPickerDialog.setMiniNumber(100.0f);
				intValue = userProfileSettings.getLTHR();// 120;//need read from db
			} else {
				numberUnitPickerDialog.setMaxNumber(220.0f);
				numberUnitPickerDialog.setMiniNumber(60.0f);
				intValue = userProfileSettings.getALAHR();// 150;//need from db user_profile3.getLTHR();
			}
			z = false;
			if (intValue == 0.0f) {
				intValue = 150.0f;
			}
			numberUnitPickerDialog.setDefaultValue(intValue);
			numberUnitPickerDialog.setUpUnitwithRange(UnitConstants.getHeartRateUnit("m"), null, 1, z);// getEntryViewModel().getUnitType()
			numberUnitPickerDialog.show();
		}

		// set heartrate and power arrange
		public final void showFTPDialog() {

			if (this.ftpPicker == null) {
				this.ftpPicker = new NumberUnitPickerDialog(getContext());
			}

			ftpPicker.setNumberPickListener(new NumberUnitPickerDialog.NumberPickListener() {
				@Override public void onDialogDismiss() {
				}

				@Override public void onNumberPick(final float f, float decimal) {
					Log.d(TAG, "wangsm_bes,showFTPDialog  f: " + f + "f2: " + decimal);
					ftpTextView.setText(f + UnitConstants.getPowerRateUnit("m"));
					if (userProfileSettings != null) {
						userProfileSettings.setFTP((int) f);
					}
					saveUserProfileSettingsJson();// userProfile
				}
			});
			ftpPicker.setMaxNumber(500.0f);
			ftpPicker.setMiniNumber(100.0f);

			float intValue = userProfileSettings.getFTP();// 0.0f;
			if (intValue == 0.0f) {
				intValue = 200.0f;
			}
			ftpPicker.setDefaultValue(intValue);
			ftpPicker.setUpUnitwithRange(UnitConstants.UNIT_POWER, null, 0, false);
			ftpPicker.show();
		}

		public void editAlertHeartRate() {
			showHRDialog(HeartRateChooseType.HR);
		}

		public void editMaxHeartRate() {
			showHRDialog(HeartRateChooseType.MAX);
		}

		public void editLTHR() {
			showHRDialog(HeartRateChooseType.LTHR);
		}

		public void editFTP() {
			showFTPDialog();
		}

		// end HR dialog
		public void editTimeZone() {
			showTimeZonePicker();
		}

		/* show alaspeed dialog */
		public final void showSpeedDialog() {
			String type = "m";
			// UserProfile userProfile = userProfileSettings.getUser_profile();
			if (speedPicker == null) {
				speedPicker = new NumberUnitPickerDialog(getContext());
			}
			float defaultSpeedValue = parseUserProfileAlaSpeed(userProfileSettings.getALASPEED());
			if (type.equals("f")) {
				NumberUnitPickerDialog numberUnitPickerDialog = this.speedPicker;
				numberUnitPickerDialog.setMaxNumber(62.0f);
				speedPicker.setMiniNumber(9.0f);
				speedPicker.setDefaultValue(defaultSpeedValue);
				speedPicker.setUpUnitwithRange(".", UnitConstants.UNIT_SPEED_MPH, 10, true);
			} else if (type.equals("m")) {
				speedPicker.setMaxNumber(SpeedUnit.LegalMetricMaxNum);
				speedPicker.setMiniNumber(SpeedUnit.LegalMetricMinNum);
				speedPicker.setDefaultValue(defaultSpeedValue);
				speedPicker.setUpUnitwithRange(".", UnitConstants.UNIT_SPEED_KMH, 10, true);
			}

			if (speedPicker != null) {
				speedPicker.setNumberPickListener(new NumberUnitPickerDialog.NumberPickListener() {
					@Override public void onDialogDismiss() {
					}

					@Override public void onNumberPick(float f, float decimal) {
						float speed = (decimal / 10) + f;
						Log.d(TAG, "wangsm_bes,speed click f: " + f + "f2: " + decimal + "f3: " + speed);
						if (speed == speedPicker.getDefaultValue()) {
							return;
						}
						// defaultSpeedValue = speed;
						speedWarningTextView.setText(speed + UnitConstants.UNIT_SPEED_KMH);

						speed = f * 10 + decimal;
						Log.d(TAG, "wangsm_bes,speed save value: " + speed);

						if (userProfileSettings != null) {
							userProfileSettings.setALASPEED((int) speed);
						}
						saveUserProfileSettingsJson();
					}
				});
				speedPicker.show();
			}
		}
		// show speed dialog

		public final void showTimeZonePicker() {
			String valueOf;
			String str;
			Long tempSave = null;
			InputHelper.hideSoftInput(requireActivity());
			if (timeZonePickerDialog == null) {
				timeZonePickerDialog = new NumberPickerDialog(getContext());
			}
			// UserProfile userProfile = userProfileSettings.getUser_profile();
			final String[] hoursArray = SGDeviceSettingSupportUtil.Companion.getHoursArray();
			final String[] minsArray = SGDeviceSettingSupportUtil.Companion.getMinsArray();
			tempSave = userProfileSettings.getTime_zone();
			if (tempSave != null) {
				long j = 3600;
				long longValue = tempSave / j;
				if (Math.abs(longValue) < 10) {
					String sb = "0" + Math.abs(longValue);
					valueOf = sb;
				} else {
					valueOf = String.valueOf(Math.abs(longValue));
				}
				if (longValue >= 0) {
					str = '+' + valueOf;
				} else {
					str = '-' + valueOf;
				}
				if (ArraysKt.contains(hoursArray, str)) {
					int indexOf = ArraysKt.indexOf(hoursArray, str);
					timeZonePickerDialog.setLeftDisplayTimeZoneValue(hoursArray, indexOf);
				} else {
					setDefaultPhoneTimeZone(hoursArray, minsArray);
				}

				long abs = (Math.abs(tempSave.longValue()) - (Math.abs(longValue) * j)) / 60;
				if (ArraysKt.contains(minsArray, String.valueOf(abs))) {
					int indexOf2 = ArraysKt.indexOf(minsArray, String.valueOf(abs));
					timeZonePickerDialog.setRightDisplayTimeZoneValue(minsArray, indexOf2);
				} else {
					timeZonePickerDialog.setRightDisplayTimeZoneValue(minsArray, 0);
				}
			} else {
				setDefaultPhoneTimeZone(hoursArray, minsArray);
			}
			timeZonePickerDialog.setNumberPickListener(new NumberPickerDialog.NumberPickListener() {
				@Override public void onDialogDismiss() {
				}

				@Override public void onNumberPick(float f) {
					Log.d(TAG, "wangsm_bes, timezone value f: " + f);
					// List split$default = StringsKt.split$default((CharSequence) String.valueOf(f), new String[]{"."},
					// false, 0, 6, (Object) null);
					String valueStr = String.valueOf(f);
					// Log.d(TAG,"wangsm_bes, timezone valueStr: "+ valueStr);
					String[] valuesArray = valueStr.split("\\.");
					// Log.d(TAG,"wangsm_bes, timezone valuesArray len: "+ valuesArray.length);
					// Log.d(TAG,"wangsm_bes, timezone valuesArray0: "+ valuesArray[0] + "valuesArray1: "+
					// valuesArray[1]);
					String str2 = hoursArray[Integer.parseInt(valuesArray[0])];
					String str3 = minsArray[Integer.parseInt(valuesArray[1])];
					Log.d(TAG, "wangsm_bes, timezone str2: " + str2 + "  str3: " + str3);
					timeZoneTextView.setText(str2 + ":" + str3);
					long parseLong = Long.parseLong(str2);
					long parseLong2 = Long.parseLong(str3);
					Log.d(TAG, "wangsm_bes, timezone parseLong: " + parseLong + "  parseLong2: " + parseLong2);
					final Ref.LongRef longRef = new Ref.LongRef();
					longRef.element = (Math.abs(parseLong) * 3600) + (Math.abs(parseLong2) * 60);
					if (parseLong < 0) {
						longRef.element *= -1;
					}
					// tempSave = longRef.element;
					Log.d(TAG, "wangsm_bes, timezone longRef.element: " + longRef.element);
					// save to user_profile.json
					if (userProfileSettings != null && userProfileSettings.getTime_zone() != longRef.element) {
						userProfileSettings.setTime_zone(longRef.element);
					}
					saveUserProfileSettingsJson();// userProfile
				}
			});

			timeZonePickerDialog.show();
		}
		// set timezone

		// end settimezone
		public final void setDefaultPhoneTimeZone(String[] hoursArray, String[] minsArray) {
			String valueOf;
			String str;

			TimeZone timeZone = TimeZone.getDefault();
			Log.d(TAG, "setDefaultPhoneTimeZone, raw offset: " + timeZone.getRawOffset());
			int rawOffset = timeZone.getRawOffset() / 3600000;
			Log.d(TAG, "setDefaultPhoneTimeZone, rawOffset: " + rawOffset);
			if (Math.abs(rawOffset) < 10) {
				String sb = "0" + Math.abs(rawOffset);
				valueOf = sb;
			} else {
				valueOf = String.valueOf(Math.abs(rawOffset));
			}
			if (rawOffset >= 0) {
				str = '+' + valueOf;
			} else {
				str = '-' + valueOf;
			}
			Log.d(TAG, "setDefaultPhoneTimeZone, str: " + str);
			if (ArraysKt.contains(hoursArray, str)) {// ArraysKt.contains(hoursArray, str)
				int indexOf = ArraysKt.indexOf(hoursArray, str);
				timeZonePickerDialog.setLeftDisplayTimeZoneValue(hoursArray, indexOf);
			} else {
				timeZonePickerDialog.setLeftDisplayTimeZoneValue(hoursArray, 12);
			}
			timeZonePickerDialog.setRightDisplayTimeZoneValue(minsArray, 0);
		}

		// choose gender dialog
		public final void showGenderChooseDialog(Context context) {
			String[] strArr = {
				context.getResources().getString(R.string.gender_female), context.getResources().getString(R.string.gender_male)
			};
			AlertDialogBuilder alertDialogBuilder = new AlertDialogBuilder(getContext());
			alertDialogBuilder.setItems(strArr, (dialogInterface, i) -> {
				Log.d(TAG, "the gender i: " + i);
				if (userProfileSettings != null && userProfileSettings.getGender() != i) {
					userProfileSettings.setGender(i);
				}
				requestUpdate("sex", String.valueOf(i));
				saveUserProfileSettingsJson();
				gender.setText(strArr[i]);
				// end by wangsm
			});
			DialogUtil.adjustDialogGravityCenter(alertDialogBuilder.show());
		}

		private void requestUpdate(final String key, final String value) {
			BiCiCallback biCiCallback = new BiCiCallback() {
				@Override public void onResponseString(@NonNull String str3) {
					updateUserData(key, value);
				}
			};
			Map<String, Object> hashMap = new HashMap<>();
			hashMap.put(key, value);
			MyHttpClient.updateUserInfo(biCiCallback, hashMap);
		}

		private void updateUserData(String key, String value) {
			ContentValues c = new ContentValues();
			bb.lanxing.model.database.User userMy = App.getContext().getSigninUser();
			Long id = userMy.getId();
			if (SUPPORT_ITEM_NICK_NAME.equals(key)) {
				c.put(SUPPORT_ITEM_NICK_NAME, value);
			} else if ("email".equals(key)) {
				c.put("email", value);
			} else if (CommonNetImpl.SEX.equals(key)) {
				c.put("gender", value);
			} else if (SettingSupports.SUPPORT_ITEM_AGE.equals(key)) {
				c.put(SettingSupports.SUPPORT_ITEM_AGE, value);
			} else if ("avatar".equals(key)) {
				c.put("photoUrl", value);
			} else if ("height".equals(key)) {
				c.put("height", value);
			} else if ("weight".equals(key)) {
				c.put("weight", value);
			} else if ("birthday".equals(key)) {
				c.put("birthday", Long.parseLong(value));
			}
			App.getContext().setUserDataChanged(true);
			LitePal.update(bb.lanxing.model.database.User.class, c, id);
		}

		@Override public void callBack(String data) {
			Log.d(TAG, "wangsm_bes, UserProfileSettingsFragment call back");
			dismissLoading();
			initUerProfileViews();
		}

		/* save the user profile settings to json file */
		private boolean saveUserProfileSettingsJson() {// UserProfile userProfile
			boolean result = false;
			if (userProfileSettings == null) {// || userProfile == null
				Log.d(TAG, "save user profile null,return");
				return false;
			}
			// userProfileSettings.setUser_profile(userProfile);
			Calendar calendar = Calendar.getInstance();
			long updateTime = calendar.getTimeInMillis();
			Log.d(TAG, "the update time int value:  " + updateTime);
			userProfileSettings.setUpdate_at(updateTime);
			String jsonStr = FileUtils.createUserProfileSettingsJsonStr(userProfileSettings);
			result = FileUtils.writeSettingsJsonStrToFile(activity, userProfileSettings.getDevice_model(), userProfileSettings.getSn(), jsonStr, SettingsJsonUtils.USERPROFILE_JSON);
			Log.d(TAG, "save user profile settings json result: " + result);
			if (result) {
				ProtocolPresenter protocolPresenter = ProtocolPresenter.getInstance();
				protocolPresenter.getBikeWatchDataFromBesClient(ProtocolConstants.BIKEWATCH_set_personal_info, userProfileSettings.getDevice_model(), userProfileSettings.getSn());// yjx
			}
			return result;
		}
	}

	// Gear Settings
	public static class GearSettingsFragment extends BaseSettingsFragment implements View.OnClickListener {
		RecyclerView rvGear;
		TextView addNewBike;

		public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			return inflater.inflate(R.layout.fragment_gear_profile_setting, container, false);
		}

		@Override public void onActivityCreated(@Nullable Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
			if (activity == null) {
				activity = requireActivity();
			}
			rvGear = activity.findViewById(R.id.rv_gear);
			addNewBike = activity.findViewById(R.id.add_new_bike);
			GearAdapter adapter = new GearAdapter(R.layout.item_bike_profile_list);

			Gear gear1 = new Gear(true, 0, "jieante", "LX", "bike1", "bike", 10000, 2140, "50");
			Gear gear2 = new Gear(false, 0, "jieante", "LX", "bike2", "bike", 10000, 2140, "50");
			Gear gear3 = new Gear(false, 0, "jieante", "LX", "bike3", "bike", 10000, 2140, "50");
			if (mGearList == null) {
				mGearList = new ArrayList<>();
				mGearList.add(gear1);
				mGearList.add(gear2);
				mGearList.add(gear3);
			}
			adapter.setList(mGearList);
			adapter.setOnItemClickListener((adapter1, view, i) -> requireActivity().getSupportFragmentManager().beginTransaction().addToBackStack("GearSettingsFragment").replace(R.id.settings, GearEditFragment.getInstance(i)).commit());
			rvGear.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false));
			rvGear.setAdapter(adapter);
			addNewBike.setOnClickListener(view -> {
				Log.d(TAG, "bike click add new bike");
				requireActivity().getSupportFragmentManager().beginTransaction().addToBackStack("GearSettingsFragment").replace(R.id.settings, GearEditFragment.getCreateGearInstance()).commit();
			});
			Log.d(TAG, "gear list size: " + mGearList.size());
			if (mGearList != null && mGearList.size() < 3) {
				addNewBike.setVisibility(View.VISIBLE);
				addNewBike.setText(R.string.add_new_bike);
			} else {
				addNewBike.setVisibility(View.GONE);
			}
		}

		@Override public void onClick(View v) {

		}

		@Override public void callBack(String data) {

		}
	}

	// gear edit fragment
	public static class GearEditFragment extends BaseSettingsFragment implements View.OnClickListener {
		LinearLayout bikeNameEditll;
		TextView bikeName;
		TextView bikeCircum;// bikePerimeter
		LinearLayout bikeCircumll;

		LinearLayout bikeWeightEditll;
		TextView bikeWeight;
		Button saveButton;
		Button deleButton;
		Gear mGear;
		Context context;
		int index;
		NumberUnitPickerDialog weightPickerDialog;
		FragmentManager fragmentManager;

		public static GearEditFragment getInstance(Gear gear) {
			GearEditFragment gearEditFragment = new GearEditFragment();
			Bundle bundle = new Bundle();
			// Log.d(TAG,"Gear edit ,: name: "+ gear.getName());
			bundle.putParcelable("gear_obj", gear);
			// bundle.putString("bike_name", gear.getName());
			// bundle.putInt("bike_perimeter", gear.getWheel_size());
			// bundle.putInt("bike_weight", gear.getWeight());

			gearEditFragment.setArguments(bundle);
			return gearEditFragment;
		}

		public static GearEditFragment getInstance(int index) {
			GearEditFragment gearEditFragment = new GearEditFragment();
			Bundle bundle = new Bundle();
			// Log.d(TAG,"Gear edit ,: name: "+ gear.getName());
			bundle.putInt(SettingsParams.GEAR_LIST_INDEX, index);
			// bundle.putString("bike_name", gear.getName());
			// bundle.putInt("bike_perimeter", gear.getWheel_size());
			// bundle.putInt("bike_weight", gear.getWeight());

			gearEditFragment.setArguments(bundle);
			return gearEditFragment;
		}

		public static GearEditFragment getCreateGearInstance() {
			GearEditFragment gearEditFragment = new GearEditFragment();
			Bundle bundle = new Bundle();
			bundle.putString(SettingsParams.GEAR_STATUS, SettingsParams.GEAR_CREATE);
			gearEditFragment.setArguments(bundle);
			return gearEditFragment;
		}

		public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			return inflater.inflate(R.layout.fragment_gear_edit, container, false);
		}

		@Override public void onActivityCreated(@Nullable Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
			if (activity == null) {
				activity = requireActivity();
			}
			fragmentManager = activity.getSupportFragmentManager();
			context = getContext();

			bikeNameEditll = activity.findViewById(R.id.bike_name_edit_ll);
			bikeName = activity.findViewById(R.id.edit_bike_name);
			bikeNameEditll.setOnClickListener(this);

			bikeCircumll = activity.findViewById(R.id.bike_tire_circumference);
			bikeCircum = activity.findViewById(R.id.bike_perimeter);
			bikeCircumll.setOnClickListener(this);

			bikeWeightEditll = activity.findViewById(R.id.bike_weight_edit_ll);
			bikeWeight = activity.findViewById(R.id.bike_weight);
			bikeWeightEditll.setOnClickListener(this);

			saveButton = activity.findViewById(R.id.bike_save_button);
			saveButton.setOnClickListener(this);
			deleButton = activity.findViewById(R.id.bike_dele_button);
			deleButton.setOnClickListener(this);
			Bundle bundle = getArguments();

			if (bundle != null) {
				index = bundle.getInt(SettingsParams.GEAR_LIST_INDEX, -1);
				if (index != -1) {
					mGear = mGearList.get(index);// (Gear)bundle.getParcelable("gear_obj");
				}

				String status = bundle.getString(SettingsParams.GEAR_STATUS);
				if (SettingsParams.GEAR_CREATE.equals(status)) {
					mGear = new Gear(false, 0, "jieante", "LX", "BIKE", "ROADBIKE", 30900, 60, "50");
					deleButton.setVisibility(View.GONE);
				}

				if (mGearList.size() < 2) {
					deleButton.setVisibility(View.GONE);
				}

				if (mGear != null) {
					Log.d(TAG, "the bike name: " + mGear.getName());
					Log.d(TAG, "the bike wheel size: " + mGear.getWheel_size());
					Log.d(TAG, "the bike getWeight: " + mGear.getWeight());
					bikeName.setText(mGear.getName());
					bikeCircum.setText(String.valueOf(mGear.getWheel_size()));
					float weight = parseBikeWeight(mGear.getWeight());
					bikeWeight.setText(String.valueOf(weight));
				}
			}
		}

		@Override public void onClick(View v) {
			boolean result;
			int id = v.getId();
			if (id == R.id.bike_save_button) {
				Log.d(TAG, "save the gear list to json file");
				for (int i = 0; i < mGearList.size(); i++) {
					mGearList.get(i).setActivated(false);
				}
				mGear.setActivated(true);
				if (index == -1) {
					mGearList.add(mGear);
				} else {
					mGearList.set(index, mGear);
				}

				for (Gear gear : mGearList) {
					Log.d(TAG, "gear list : " + gear.toString());
				}
				String jsonStr = FileUtils.createGearProfileJsonStr(commonSettings, mGearList);
				String device_model = SettingsJsonUtils.getDeviceModel(requireContext());
				String sn = SettingsJsonUtils.getSn(requireContext());

				result = FileUtils.writeSettingsJsonStrToFile(activity, device_model, sn, jsonStr, SettingsJsonUtils.GEAR_PROFILE_JSON);
				Log.d(TAG, "save user gear settings json result: " + result);
				if (result) {
					ProtocolPresenter protocolPresenter = ProtocolPresenter.getInstance();
					protocolPresenter.getBikeWatchDataFromBesClient(ProtocolConstants.BIKEWATCH_set_bicycle_info, device_model, sn);// yjx
				}
				popBackGearSettingFragment();
			} else if (id == R.id.bike_dele_button) {
				if (mGearList != null && index != -1) {
					mGearList.remove(index);
				}
				popBackGearSettingFragment();
			} else if (id == R.id.bike_name_edit_ll) {
				Log.d(TAG, "click,edit bike name");
				showEditGearNameDialog(mGear.getName());
			} else if (id == R.id.bike_weight_edit_ll) {
				showWeightPicker();
			} else if (id == R.id.bike_tire_circumference) {
				showWheelSettingDialog();
			}
		}

		private void popBackGearSettingFragment() {
			if (fragmentManager != null && fragmentManager.getBackStackEntryCount() > 0) {
				fragmentManager.popBackStack("GearSettingsFragment", FragmentManager.POP_BACK_STACK_INCLUSIVE);
			}
		}

		// parse 30900 to 30.9
		private float parseBikeWeight(int bikeWeight) {
			float weight = 1;
			float highNum = bikeWeight / 1000;
			Log.d(TAG, "highNum: " + highNum);
			float lowNum = (bikeWeight - highNum * 1000) / 1000;
			Log.d(TAG, "lowNum: " + lowNum);
			weight = highNum + lowNum;
			Log.d(TAG, "weight: " + weight);

			return weight;
		}

		@Override public void callBack(String data) {

		}

		private final int dip2Px(float f) {
			return (int) ((f * requireContext().getResources().getDisplayMetrics().density) + 0.5f);
		}

		public final void showEditGearNameDialog(String bikename) {
			Gear gear;
			String name;
			final EditText editText = new EditText(getContext());
			editText.setPadding(dip2Px(12.0f), dip2Px(10.0f), dip2Px(12.0f), dip2Px(10.0f));
			editText.setText(bikename);
			editText.setMaxLines(1);
			editText.setSingleLine(true);
			editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(20) });
			AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
			builder.setTitle(R.string.st_edit_name);
			builder.setView(editText);
			builder.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
				@Override public void onClick(DialogInterface dialogInterface, int i) {
					String newName = editText.getText().toString();
					mGear.setName(newName);
					bikeName.setText(mGear.getName());
					// save the db
				}
			});
			builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
				@Override // android.content.DialogInterface.OnClickListener
				public void onClick(DialogInterface dialogInterface, int i) {

				}
			});
			builder.show();
		}

		// showWeightPicker
		public final void showWeightPicker() {// final WeightUnit unit
			String type = "m";
			InputHelper.hideSoftInput(requireActivity());
			if (weightPickerDialog == null) {
				weightPickerDialog = new NumberUnitPickerDialog(getContext());
			}

			if (type.equals("f")) {
				weightPickerDialog.setMaxNumber(80.0f);
				weightPickerDialog.setMiniNumber(1.0f);
				weightPickerDialog.setDefaultValue(15.0f);
				weightPickerDialog.setUpUnitwithRange(".", UnitConstants.UNIT_WEIGHT_LIBRA, 10, false);
			} else {

				if (type.equals("m")) {
					weightPickerDialog.setMaxNumber(50.0f);
					weightPickerDialog.setMiniNumber(1.0f);
					float weight = parseBikeWeight(mGear.getWeight());
					weightPickerDialog.setDefaultValue(weight);
					weightPickerDialog.setUpUnitwithRange(".", UnitConstants.UNIT_WEIGHT_KG, 10, false);
				}
			}
			weightPickerDialog.setNumberPickListener(new NumberUnitPickerDialog.NumberPickListener() {
				@Override public void onDialogDismiss() {
				}

				@Override public void onNumberPick(float f, float decimal) {
					Log.d(TAG, "bike weight number pick: f: " + f + "f2: " + decimal);

					int weightValue = (int) (f * 1000 + decimal * 100);
					Log.d(TAG, "bike weight weightValue: " + weightValue);
					mGear.setWeight(weightValue);
					String valueOf = String.valueOf((decimal / 10) + f);
					bikeWeight.setText(valueOf);
				}
			});
			weightPickerDialog.show();
		}

		public final void showWheelSettingDialog() {
			Intent intent = new Intent(context, WheelLengthSettingActivity.class);
			intent.putExtra("size", mGear.getWheel_size());
			startActivityForResult(intent, REQ_WHEEL_CIRCUM_EDIT_CODE);
		}

		@Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
			super.onActivityResult(requestCode, resultCode, data);
			Log.d(TAG, "gear requestcode: " + requestCode + "resultCode: " + resultCode);
			if (requestCode == REQ_WHEEL_CIRCUM_EDIT_CODE && resultCode == -1) {
				final Float valueOf = data != null ? data.getFloatExtra("wheelDiameterLength", 0.0f) : null;
				if (valueOf != null) {
					boolean z = false;
					if (mGear != null) {
						int wheel_size = mGear.getWheel_size();
						int floatValue = (int) (valueOf * 1000);
						if (wheel_size == floatValue) {
							return;
						}
					}
					mGear.setWheel_size((int) (valueOf * 1000));
					bikeCircum.setText(String.valueOf(mGear.getWheel_size()));
				}
			}
		}
	}

	public static abstract class BaseSettingsFragment extends Fragment {
		FragmentActivity activity;
		CircularProgressDialog progressDialog;
		private ActionBar mActionBar;
		private String mTitle;

		public String getTitle() {
			return mTitle;
		}

		public void setTitle(String title) {
			mTitle = title;
		}

		public ActionBar getActionBar() {
			return mActionBar;
		}

		public void setActionBar(ActionBar actionBar) {
			mActionBar = actionBar;
		}

		public abstract void callBack(String data);

		public void showLoading(Context context, int id) {
			if (context == null) {
				Log.d(TAG, "show loading,context is null,return");
				return;
			}
			Log.i(TAG, "showLoading");
			if (progressDialog == null) {
				progressDialog = new CircularProgressDialog(context, false, false, null);
			}
			progressDialog.show(id);
		}

		public void dismissLoading() {
			if (progressDialog != null) {
				progressDialog.dismiss();
				progressDialog = null;
			}
		}

		protected void goTargetFragment(@NonNull Fragment fragment) {
			requireActivity().getSupportFragmentManager().beginTransaction().addToBackStack(this.getClass().getSimpleName()).replace(R.id.settings, fragment).commit();
		}

		@Override public void onDestroy() {
			dismissLoading();
			super.onDestroy();
		}
	}
}